package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.util.PermissionAnnotation;
import cn.wolfcode.web.util.SessionUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断静动态资源
        if (handler instanceof HandlerMethod) {
            Employee user = SessionUtil.getAtt(SessionUtil.USER);
            //判断是否超级管理员
            if (user.getAdmin()){
                System.out.println(user.getAdmin());
                return true;
            }
            //获取所有权限集合
            List<Permission> permissions = SessionUtil.getAttr(SessionUtil.PERMISSION);
           //拿到动态方法
            Method method = ((HandlerMethod) handler).getMethod();
            //获取贴注解的方法
            PermissionAnnotation annotation = method.getAnnotation(PermissionAnnotation.class);

            //没贴注解的方法 直接放行
            if (annotation==null){
                return true;
            }
            //判断该角色具有哪些权限
            for (Permission permission : permissions) {
                if (permission.getExpression().equals(annotation.expression())) {
                    return true;
                }
            }

            //判断是哪种请求
            ResponseBody responseBody = method.getAnnotation(ResponseBody.class);
            if (responseBody==null){
                //没有注解 跳转页面
                response.sendRedirect("/permission/noPermission");
            }else {
                //有注解 跳出弹框
                //设置响应头格式 为json格式
                response.setContentType("application/json;charset=utf-8");
                String jsonResult = JSON.toJSONString(new JsonResult("您没有权限访问", false));
                response.getWriter().write(jsonResult);
            }


            return false;
        }
        return true;
    }
}
